//
//  EVEAPIImageDownloader.m
//  EVE Mac Suite
//
//  Created by Vadim Lozko on 2/10/09.
//  Copyright 2009 __Vadim__. All rights reserved.
//

#import "EVEAPIImageDownloader.h"
#import "EVEAPIDownloaderRequest.h"

@implementation EVEAPIImageDownloader

-(NSString*)server
{
	return [[EMSGeneralUtils urlConstants] objectForKey:@"ImageServer"];
}
/*
-(void)performDownloadWithRequest:(NSURLRequest*)request
{
	
	NSError* error = nil;
	NSAutoreleasePool* downloaderPool = [[NSAutoreleasePool alloc] init];
	NSURLResponse* response = [[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/jepg" expectedContentLength:-1 textEncodingName:nil] autorelease];
	NSData* downloadedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	if([downloadedData length] == 0)
	{
		//TODO:implement
	} else {
		if(error)
		{
			NSLog(@"Error: %@", error);
		} else {
			if([delegate respondsToSelector:@selector(downloadRequestDidFinishForImageData:)])
			{
				[delegate performSelectorOnMainThread:@selector(downloadRequestDidFinishForImageData:)
										   withObject:downloadedData 
										waitUntilDone:NO];
			}
		}
		[requestQueue removeLastObject];
	}
	[downloaderPool release];
}*/

-(void)performNextRequest
{
	if([requestQueue count] == 1)
	{
		EVEAPIDownloaderRequest* nextRequest = [requestQueue objectAtIndex:0];
		NSString* requestType = [nextRequest type];
		NSDictionary* info = [nextRequest info];
		NSString* postString = [self postStringForUserID:nil 
												  apiKey:nil
											 characterID:[info objectForKey:CHAR_INFO_DICT_CHARID]
											   pixelSize:[info objectForKey:CHAR_INFO_DICT_PIXELSIZE]];
		NSString* requestString = [NSString stringWithFormat:@"%@%@%@",
								   [self server],[[EMSGeneralUtils urlConstants] objectForKey:requestType], postString];
		NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestString]];
		//[NSThread detachNewThreadSelector:@selector(performDownloadWithRequest:) toTarget:self withObject:request];
		[self performDownloadWithRequest:request];
	}
	
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	id handler = [[requestQueue objectAtIndex:0] handler];
	[handler downloadRequestDidFinishForImageData:receivedData];
	[receivedData release];
	[self popQueue];
	[self performNextRequest];
	//[self performSelector:@selector(performNextRequest) withObject:nil afterDelay:.1];
}

@end
